﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using Entity = Savico.Library.Entity;
using Business = Savico.Library.Business;

public partial class templates_admin_usercontrols_list_news : System.Web.UI.UserControl
{
    Entity.TinTuc entityNews = new Savico.Library.Entity.TinTuc();
    Entity.DanhMuc entityCategory = new Savico.Library.Entity.DanhMuc();
    Business.DanhMuc businessCategory = new Savico.Library.Business.DanhMuc();
    Business.TinTuc businessNews = new Savico.Library.Business.TinTuc();
    string ngonngu = "vi";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            entityCategory.NgonNgu = "vi";
            entityNews.NgonNgu = "vi";
            LoadChuyenMuc(0);
            dtNews = businessNews.SelectTheoNgonNgu(entityNews);
            Load_News();
        }
    }
    // Load chuyên mục tin tức
    private void LoadChuyenMuc(int IdDanhMuc)
    {
        entityCategory.IdDanhMuc = IdDanhMuc;
        DataTable dt = businessCategory.SelectTheoCap(entityCategory);
        if (dt.Rows.Count > 0)
        {
            foreach (DataRow dr in dt.Rows)
            {
                int id = (int)dr["IdDanhMuc"];
                string name = dr["TenDanhMuc"].ToString();
                int level = (int)dr["Cap"];
                string sub = "";
                for (int i = 1; i <= level; i++)
                {
                    sub += "---";
                }
                name = sub + name;
                ListItem item = new ListItem(name, id.ToString());
                ddlChuyenMuc.Items.Add(item);
                LoadChuyenMuc(id);
            }
        }
    }
    // Load Tin tức
    private void Load_News()
    {
        if (dtNews.Rows.Count == 0)
        {
            BindItemsList(dtNews);
            PhanTrang.Visible = false;
            msgNoRows.Style.Add("display", "block");
        }
        else if (dtNews.Rows.Count > 0 && dtNews.Rows.Count <= 3)
        {
            BindItemsList(dtNews);
            PhanTrang.Visible = false;
            msgNoRows.Style.Add("display", "none");
        }
        else if (dtNews.Rows.Count > 3)
        {
            BindItemsList(dtNews);
            PhanTrang.Visible = true;
            msgNoRows.Style.Add("display", "none");
        }
    }
    #region Phân trang bằng PagedDataSource
    private static DataTable dtNews = new DataTable();
    //Khái báo các property trang, chỉ số đầu, chỉ số cuối
    private int CurrentPage
    {
        get
        {
            object objPage = ViewState["_CurrentPage"];

            int _CurrentPage = 0;
            if (objPage == null)
            {
                _CurrentPage = 0;
            }
            else
            {
                _CurrentPage = (int)objPage;
            }
            return _CurrentPage;
        }
        set { ViewState["_CurrentPage"] = value; }
    }
    private int fistIndex
    {
        get
        {

            int _FirstIndex = 0;
            if (ViewState["_FirstIndex"] == null)
            {
                _FirstIndex = 0;
            }
            else
            {
                _FirstIndex = Convert.ToInt32(ViewState["_FirstIndex"]);
            }
            return _FirstIndex;
        }
        set { ViewState["_FirstIndex"] = value; }
    }
    private int lastIndex
    {
        get
        {
            int _LastIndex = 0;
            if (ViewState["_LastIndex"] == null)
            {
                _LastIndex = 0;
            }
            else
            {
                _LastIndex = Convert.ToInt32(ViewState["_LastIndex"]);
            }
            return _LastIndex;
        }
        set { ViewState["_LastIndex"] = value; }
    }

    PagedDataSource _PageDataSource = new PagedDataSource();

    //Load dữ liệu và phân trang cho dữ liệu
    private void BindItemsList(DataTable dt)
    {
        DataTable dataTable = dt;
        _PageDataSource.DataSource = dataTable.DefaultView;
        _PageDataSource.AllowPaging = true;
        _PageDataSource.PageSize = 10;
        _PageDataSource.CurrentPageIndex = CurrentPage;
        ViewState["TotalPages"] = _PageDataSource.PageCount;

        this.lblPageInfo.Text = "Trang " + (CurrentPage + 1) + " của " + _PageDataSource.PageCount;
        this.lbtnPrevious.Enabled = !_PageDataSource.IsFirstPage;
        this.lbtnNext.Enabled = !_PageDataSource.IsLastPage;
        this.lbtnFirst.Enabled = !_PageDataSource.IsFirstPage;
        this.lbtnLast.Enabled = !_PageDataSource.IsLastPage;

        this.rptDanhSachTinTuc.DataSource = _PageDataSource;
        this.rptDanhSachTinTuc.DataBind();
        this.doPaging();
    }
    //Phân trang
    private void doPaging()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("PageIndex");
        dt.Columns.Add("PageText");
        fistIndex = CurrentPage - 5;
        if (CurrentPage > 5)
        {
            lastIndex = CurrentPage + 5;
        }
        else
        {
            lastIndex = 10;
        }
        if (lastIndex > Convert.ToInt32(ViewState["TotalPages"]))
        {
            lastIndex = Convert.ToInt32(ViewState["TotalPages"]);
            fistIndex = lastIndex - 10;
        }
        if (fistIndex < 0)
        {
            fistIndex = 0;
        }
        for (int i = fistIndex; i < lastIndex; i++)
        {
            DataRow dr = dt.NewRow();
            dr[0] = i;
            dr[1] = i + 1;
            dt.Rows.Add(dr);
        }
        this.dlPaging.DataSource = dt;
        this.dlPaging.DataBind();
    }

    //Trang dầu tiên
    protected void lbtnFirst_Click(object sender, EventArgs e)
    {
        CurrentPage = 0;
        BindItemsList(dtNews);
    }
    //Trang sau trang đang hiển thị
    protected void lbtnPrevious_Click(object sender, EventArgs e)
    {
        CurrentPage -= 1;
        BindItemsList(dtNews);
    }
    //Trang tiếp theo trang đang hiển thị
    protected void lbtnNext_Click(object sender, EventArgs e)
    {
        CurrentPage += 1;
        BindItemsList(dtNews);
    }
    //Trang cuối
    protected void lbtnLast_Click(object sender, EventArgs e)
    {
        CurrentPage = (Convert.ToInt32(ViewState["TotalPages"]) - 1);
        BindItemsList(dtNews);
    }
    //Hàm sự kiện dlPaging
    protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.Equals("Paging"))
        {
            CurrentPage = Convert.ToInt32(e.CommandArgument.ToString());
            BindItemsList(dtNews);
        }
    }
    protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("lnkbtnPaging");
        if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
        {
            lnkbtnPage.Enabled = false;
            //lnkbtnPage.Style.Add("fone-size", "14px");
            //lnkbtnPage.Font.Bold = true;
            lnkbtnPage.CssClass = "active";
        }
    }
    #endregion
    // Tìm kiếm
    private void TimKiem(int Opt)
    {
        entityNews.Option = Opt;
        dtNews = businessNews.SelectTimKiem(entityNews);
        Load_News();
    }
    // Chuyển đổi ngôn ngữ
    private void ChuyenDoiNgonNgu_btn()
    {
        try
        {
            foreach (RepeaterItem ListItem in rptDanhSachTinTuc.Items)
            {
                Label lbNoiDung = (Label)ListItem.FindControl("lbNoiDung");
                Label lbDanhMuc = (Label)ListItem.FindControl("lbDanhMuc");
                Label lbNgayViet = (Label)ListItem.FindControl("lbNgayViet");
                Label lbNguoiDang = (Label)ListItem.FindControl("lbNguoiDang");
                Label lbLuotXem = (Label)ListItem.FindControl("lbLuotXem");
                Label lbTrangThai = (Label)ListItem.FindControl("lbTrangThai");
                HyperLink hplSua = (HyperLink)ListItem.FindControl("hplSua");
                LinkButton lbXoa = (LinkButton)ListItem.FindControl("lbXoa");
                LinkButton hbTrangThai = (LinkButton)ListItem.FindControl("hbTrangThai");
                if (btnThem.Text == "Thêm")
                {
                    lbNoiDung.Text = "Nôi dung : ";
                    lbDanhMuc.Text = "Chuyên mục : ";
                    lbNguoiDang.Text = "Viết bởi : ";
                    lbNgayViet.Text = "Ngày viết : ";
                    lbLuotXem.Text = "Lượt xem : ";
                    lbTrangThai.Text = "Trạng thái : ";
                    hplSua.Text = "Sửa";
                    lbXoa.Text = "Xóa";
                    hbTrangThai.Text = "Trạng thái";
                }
                if (btnThem.Text == "Add")
                {
                    lbNoiDung.Text = "Content : ";
                    lbDanhMuc.Text = "Category : ";
                    lbNguoiDang.Text = "Author : ";
                    lbNgayViet.Text = "Posted : ";
                    lbLuotXem.Text = "Views : ";
                    lbTrangThai.Text = "Status : ";
                    hplSua.Text = "Repair";
                    lbXoa.Text = "Delete";
                    hbTrangThai.Text = "Status";
                }
            }
            if (btnThem.Text == "Thêm")
            {
                lbTitle.Text = "Danh sách tin tức";
                btnLamMoi.Text = "Làm mới";
                btnThem.Text = "Thêm";
                btnTim.Text = "Tìm";
                lbtnFirst.Text = "Đầu";
                lbtnLast.Text = "Cuối";
                lbtnNext.Text = "Tiếp";
                lbtnPrevious.Text = "Trước";
                txtTuKhoaEn.Visible = false;
                txtTuKhoaVn.Visible = true;
            }
            if (btnThem.Text == "Add")
            {
                lbTitle.Text = "List news";
                btnLamMoi.Text = "Refresh";
                btnThem.Text = "Add";
                btnTim.Text = "Search";
                lbtnFirst.Text = "First";
                lbtnLast.Text = "Last";
                lbtnNext.Text = "Next";
                lbtnPrevious.Text = "Previous";
                txtTuKhoaEn.Visible = true;
                txtTuKhoaVn.Visible = false;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }

    }
    private void ChuyenDoiNgonNgu()
    {
        try
        {
            foreach (RepeaterItem ListItem in rptDanhSachTinTuc.Items)
            {
                Label lbNoiDung = (Label)ListItem.FindControl("lbNoiDung");
                Label lbDanhMuc = (Label)ListItem.FindControl("lbDanhMuc");
                Label lbNgayViet = (Label)ListItem.FindControl("lbNgayViet");
                Label lbNguoiDang = (Label)ListItem.FindControl("lbNguoiDang");
                Label lbLuotXem = (Label)ListItem.FindControl("lbLuotXem");
                Label lbTrangThai = (Label)ListItem.FindControl("lbTrangThai");
                HyperLink hplSua = (HyperLink)ListItem.FindControl("hplSua");
                LinkButton lbXoa = (LinkButton)ListItem.FindControl("lbXoa");
                LinkButton hbTrangThai = (LinkButton)ListItem.FindControl("hbTrangThai");
                if (ngonngu == "vi")
                {
                    lbNoiDung.Text = "Nôi dung : ";
                    lbDanhMuc.Text = "Chuyên mục : ";
                    lbNguoiDang.Text = "Viết bởi : ";
                    lbNgayViet.Text = "Ngày viết : ";
                    lbLuotXem.Text = "Lượt xem : ";
                    lbTrangThai.Text = "Trạng thái : ";
                    hplSua.Text = "Sửa";
                    lbXoa.Text = "Xóa";
                    hbTrangThai.Text = "Trạng thái";
                }
                if (ngonngu == "en")
                {
                    lbNoiDung.Text = "Content : ";
                    lbDanhMuc.Text = "Category : ";
                    lbNguoiDang.Text = "Author : ";
                    lbNgayViet.Text = "Posted : ";
                    lbLuotXem.Text = "Views : ";
                    lbTrangThai.Text = "Status : ";
                    hplSua.Text = "Repair";
                    lbXoa.Text = "Delete";
                    hbTrangThai.Text = "Status";
                }
            }
            if (ngonngu == "vi")
            {
                lbTitle.Text = "Danh sách tin tức";
                btnLamMoi.Text = "Làm mới";
                btnThem.Text = "Thêm";
                btnTim.Text = "Tìm";
                lbtnFirst.Text = "Đầu";
                lbtnLast.Text = "Cuối";
                lbtnNext.Text = "Tiếp";
                lbtnPrevious.Text = "Trước";
                txtTuKhoaEn.Visible = false;
                txtTuKhoaVn.Visible = true;
                
            }
            if (ngonngu == "en")
            {
                lbTitle.Text = "List news";
                btnLamMoi.Text = "Refresh";
                btnThem.Text = "Add";
                btnTim.Text = "Search";
                lbtnFirst.Text = "First";
                lbtnLast.Text = "Last";
                lbtnNext.Text = "Next";
                lbtnPrevious.Text = "Previous";
                txtTuKhoaEn.Visible = true;
                txtTuKhoaVn.Visible = false;
              
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }

    }
    protected void btnThem_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/admin/AddNews.aspx?action=add");
    }
    protected void btnLamMoi_Click(object sender, EventArgs e)
    {
        if (btnThem.Text == "Thêm")
        {
            DeleteItemDDL();
            entityNews.NgonNgu = "vi";
            entityCategory.NgonNgu = "vi";
            LoadChuyenMuc(0);
            dtNews = businessNews.SelectTheoNgonNgu(entityNews);
            Load_News();
            ChuyenDoiNgonNgu_btn();
        }
        if (btnThem.Text == "Add")
        {
            DeleteItemDDL();
            entityNews.NgonNgu = "en";
            entityCategory.NgonNgu = "en";
            LoadChuyenMuc(0);
            dtNews = businessNews.SelectTheoNgonNgu(entityNews);
            Load_News();
            ChuyenDoiNgonNgu_btn();
        }
    }
    private void DeleteItemDDL()
    {  
        for (int i = 0; i < ddlChuyenMuc.Items.Count;)
        {
            ddlChuyenMuc.Items.RemoveAt(i);
        }
    }
    protected void btnTim_Click(object sender, EventArgs e)
    {
        entityNews.ChuyenMuc = Convert.ToInt32(ddlChuyenMuc.SelectedValue);
        if (btnThem.Text == "Add")
        {
            entityNews.KeySearch = txtTuKhoaEn.Text;
            entityNews.NgonNgu = "en";
            if (txtTuKhoaEn.Text != "Keyword..." && (ddlChuyenMuc.SelectedValue == "0" || ddlChuyenMuc.SelectedValue == "-1"))
            {
                TimKiem(0);
            }
            else if (txtTuKhoaEn.Text == "Keyword..." && ddlChuyenMuc.SelectedValue != "0" && ddlChuyenMuc.SelectedValue != "-1")
            {
                TimKiem(1);
            }
            else if (txtTuKhoaEn.Text != "Keyword..." && ddlChuyenMuc.SelectedValue != "0" && ddlChuyenMuc.SelectedValue != "-1")
            {
                TimKiem(2);
            }
            else
            {
                Alert.Show("Please enter keyword or select category !!!");
                dtNews = businessNews.SelectTheoNgonNgu(entityNews);
                Load_News();
            }
            DeleteItemDDL();
            entityCategory.NgonNgu = "en";
            ListItem item = new ListItem("------Search by category------", "-1");
            ddlChuyenMuc.Items.Add(item);
            LoadChuyenMuc(0);
            ChuyenDoiNgonNgu_btn();
        }
        if (btnThem.Text == "Thêm")
        {
            entityNews.KeySearch = txtTuKhoaVn.Text;
            entityNews.NgonNgu = "vi";
            if (txtTuKhoaVn.Text != "Từ khóa..." && (ddlChuyenMuc.SelectedValue == "0" || ddlChuyenMuc.SelectedValue == "-1"))
            {
                TimKiem(0);
            }
            else if (txtTuKhoaVn.Text == "Từ khóa..." && ddlChuyenMuc.SelectedValue != "0" && ddlChuyenMuc.SelectedValue != "-1")
            {
                TimKiem(1);
            }
            else if (txtTuKhoaVn.Text != "Từ khóa..." && ddlChuyenMuc.SelectedValue != "0" && ddlChuyenMuc.SelectedValue != "-1")
            {
                TimKiem(2);
            }
            else
            {
                Alert.Show("Bạn chưa nhập từ khóa hoặc chưa chọn chuyên mục cần tìm !!!");
                dtNews = businessNews.SelectTheoNgonNgu(entityNews);
                Load_News();
            }
            DeleteItemDDL();
            entityCategory.NgonNgu = "vi";
            ListItem item = new ListItem("------Tìm theo chuyên mục------", "-1");
            ddlChuyenMuc.Items.Add(item);
            LoadChuyenMuc(0);
            ChuyenDoiNgonNgu_btn();
        }
    }
  
    protected void btnTiengViet_Click(object sender, EventArgs e)
    {
        DeleteItemDDL();
        ngonngu = "vi";
        entityCategory.NgonNgu = "vi";
        entityNews.NgonNgu = "vi";
        ListItem item = new ListItem("------Tìm theo chuyên mục------", "-1");
        ddlChuyenMuc.Items.Add(item);
        LoadChuyenMuc(0);
        dtNews = businessNews.SelectTheoNgonNgu(entityNews);
        Load_News();
        
        ChuyenDoiNgonNgu();
    }
    protected void btnTiengAnh_Click(object sender, EventArgs e)
    {
        DeleteItemDDL();
        ngonngu = "en";
        entityCategory.NgonNgu = "en";
        entityNews.NgonNgu = "en";
        ListItem item = new ListItem("------Search by category------", "-1");
        ddlChuyenMuc.Items.Add(item);
        LoadChuyenMuc(0);
        dtNews = businessNews.SelectTheoNgonNgu(entityNews);
        Load_News();
       
        ChuyenDoiNgonNgu();
    }
    protected void rptDanhSachTinTuc_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        try
        {
            //Nếu click nút xóa từ danh sách
            if (e.CommandName == "xoa")
            {
                bool delete = false;
                string filename = "";
                entityNews.IdTinTuc = Convert.ToInt32(e.CommandArgument.ToString());
                DataTable dt = businessNews.SelectPrimaryKey(entityNews);
                filename = dt.Rows[0]["HinhAnh"].ToString();
                delete = businessNews.Delete(entityNews);
                if (delete)
                {
                    File.Delete(Server.MapPath("~/uploads/image-news/" + filename));
                    if (btnThem.Text == "Thêm")
                    {
                        entityNews.NgonNgu = "vi";
                        Alert.Show("Xóa bài viết thành công !!!");
                        dtNews = businessNews.SelectTheoNgonNgu(entityNews);
                        Load_News();
                        ChuyenDoiNgonNgu_btn();
                    }
                    if (btnThem.Text == "Add")
                    {
                        entityNews.NgonNgu = "en";
                        Alert.Show("Delete news success !!!");
                        dtNews = businessNews.SelectTheoNgonNgu(entityNews);
                        Load_News();
                        ChuyenDoiNgonNgu_btn();
                    }
                }
                else
                { Alert.Show("Xóa bài viết không thành công!"); }

            }
            if (e.CommandName == "statusupdate")
            {
                try
                {
                    bool trangthai = false;
                    entityNews.IdTinTuc = Convert.ToInt32(e.CommandArgument.ToString());
                    if (btnThem.Text == "Thêm")
                    {
                        entityNews.NgonNgu = "vi";
                        trangthai = businessNews.Update_TrangThai(entityNews);
                        if (trangthai)
                        {
                            Alert.Show("Cập nhật trạng thái thành công !!!");
                            dtNews = businessNews.SelectTheoNgonNgu(entityNews);
                            Load_News();
                            ChuyenDoiNgonNgu_btn();
                        }
                    }
                    if (btnThem.Text == "Add")
                    {
                        entityNews.NgonNgu = "en";
                        trangthai = businessNews.Update_TrangThai(entityNews);
                        if (trangthai)
                        {
                            Alert.Show("Update status success !!!");
                            dtNews = businessNews.SelectTheoNgonNgu(entityNews);
                            Load_News();
                            ChuyenDoiNgonNgu_btn();
                        }
                    }
                    else
                    { Alert.Show("Cập nhật trạng thái không thành công!"); }
                }
                catch
                { }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}
